import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import { Notice, noticeService } from "@/api/services/noticeService";
import {
	Button,
	Card,
	Form,
	Input,
	Modal,
	message,
	Select,
	Space,
	Table,
	Tag,
	Tooltip,
	Typography,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import dayjs from "dayjs";

const { TextArea } = Input;

const statusMap = {
	0: { text: "禁用", color: "error" },
	1: { text: "启用", color: "success" },
};

export default function NoticeListPage() {
	const [loading, setLoading] = useState(false);
	const [records, setRecords] = useState<Notice[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [modalTitle, setModalTitle] = useState("新增通知");
	const [editingRecord, setEditingRecord] = useState<Notice>();
	const [form] = Form.useForm();
	const [searchForm] = Form.useForm();

	const fetchRecords = async (page = 1, limit = 10) => {
		setLoading(true);
		const values = await searchForm.validateFields();
		const res = await noticeService.noticeList({ page, limit, ...values });
		setRecords(res.items);
		setTotal(res.total);
		setLoading(false);
	};

	useEffect(() => {
		fetchRecords(currentPage, pageSize);
	}, [currentPage, pageSize]);

	const handleAdd = () => {
		setModalTitle("新增通知");
		setEditingRecord(undefined);
		form.resetFields();
		setModalVisible(true);
	};

	const handleEdit = (record: Notice) => {
		setModalTitle("编辑通知");
		setEditingRecord(record);
		form.setFieldsValue(record);
		setModalVisible(true);
	};

	const handleDelete = (record: Notice) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除该通知吗？",
			onOk: async () => {
				try {
					const res = await noticeService.noticeDelete(record.id);
					message.success("删除成功");
					fetchRecords(currentPage, pageSize);
				} catch (error) {
					message.error("删除失败");
				}
			},
		});
	};

	const handleChangeStatus = async (record: Notice) => {
		try {
			const res = await noticeService.noticeChangeStatus(
				record.id,
				record.status === 1 ? 0 : 1,
			);
			message.success("状态修改成功");
			fetchRecords(currentPage, pageSize);
		} catch (error) {
			message.error("状态修改失败");
		}
	};

	const handleSubmit = async () => {
		try {
			const values = await form.validateFields();
			let res;
			if (editingRecord) {
				res = await noticeService.noticeEdit(editingRecord.id, values);
			} else {
				res = await noticeService.noticeAdd(values);
			}
			message.success(editingRecord ? "更新成功" : "添加成功");
			fetchRecords(currentPage, pageSize);
			setModalVisible(false);
		} catch (error) {
			message.error(editingRecord ? "更新失败" : "添加失败");
		}
	};

	const columns: ColumnsType<Notice> = [
		{
			title: "通知标题",
			dataIndex: "title",
			width: 200,
			ellipsis: true,
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: "通知内容",
			dataIndex: "content",
			ellipsis: true,
			render: (text) => (
				<Typography.Paragraph ellipsis={{ rows: 2, tooltip: text }}>
					{text}
				</Typography.Paragraph>
			),
		},
		{
			title: "首页显示",
			dataIndex: "is_home",
			width: 100,
			render: (is_home) => (
				<Tag color={is_home === 1 ? "success" : "default"}>
					{is_home === 1 ? "是" : "否"}
				</Tag>
			),
		},
		{
			title: "状态",
			dataIndex: "status",
			width: 100,
			render: (status) => (
				<Tag color={statusMap[status]?.color}>{statusMap[status]?.text}</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			width: 180,
			render: (createtime) => (
				<span>{dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
			),
		},
		{
			title: "更新时间",
			dataIndex: "updatetime",
			width: 180,
			render: (updatetime) => (
				<span>{dayjs(updatetime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
			),
		},
		{
			title: "操作",
			key: "action",
			width: 180,
			fixed: "right",
			render: (_, record) => (
				<Space>
					<Tooltip title="编辑">
						<IconButton onClick={() => handleEdit(record)}>
							<Iconify icon="material-symbols:edit-outline" />
						</IconButton>
					</Tooltip>
					{/* <Tooltip title={record.status === 1 ? "禁用" : "启用"}>
						<IconButton onClick={() => handleChangeStatus(record)}>
							<Iconify
								icon={
									record.status === 1
										? "material-symbols:block"
										: "material-symbols:check-circle-outline"
								}
							/>
						</IconButton>
					</Tooltip> */}
					<Tooltip title="删除">
						<IconButton onClick={() => handleDelete(record)}>
							<Iconify icon="material-symbols:delete-outline" />
						</IconButton>
					</Tooltip>
				</Space>
			),
		},
	];

	return (
		<div style={{ padding: "24px", background: "#f5f5f5", minHeight: "100vh" }}>
			<Card bordered={false} style={{ borderRadius: "12px" }}>
				<div
					style={{
						marginBottom: "24px",
						display: "flex",
						alignItems: "center",
						justifyContent: "space-between",
					}}
				>
					<Typography.Title level={4} style={{ margin: 0 }}>
						通知管理
					</Typography.Title>
					<Button
						type="primary"
						icon={<Iconify icon="material-symbols:add" />}
						onClick={handleAdd}
					>
						新增通知
					</Button>
				</div>

				<Table
					rowKey="id"
					columns={columns}
					dataSource={records}
					loading={loading}
					pagination={{
						current: currentPage,
						pageSize,
						total,
						onChange: (page, size) => {
							setCurrentPage(page);
							setPageSize(size);
						},
						style: { marginTop: "24px" },
					}}
					scroll={{ x: 800 }}
				/>
			</Card>

			<Modal
				title={
					<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
						<Iconify
							icon={
								editingRecord
									? "material-symbols:edit-outline"
									: "material-symbols:add"
							}
						/>
						<span>{modalTitle}</span>
					</div>
				}
				open={modalVisible}
				onCancel={() => setModalVisible(false)}
				onOk={handleSubmit}
				width={600}
			>
				<Form
					form={form}
					layout="vertical"
					initialValues={{ status: 1, is_home: 0 }}
					style={{ padding: "24px 0" }}
				>
					<Form.Item
						name="title"
						label="通知标题"
						rules={[{ required: true, message: "请输入通知标题" }]}
					>
						<Input placeholder="请输入通知标题" />
					</Form.Item>

					<Form.Item
						name="content"
						label="通知内容"
						rules={[{ required: true, message: "请输入通知内容" }]}
					>
						<TextArea rows={4} placeholder="请输入通知内容" />
					</Form.Item>

					<Form.Item
						name="is_home"
						label="首页显示"
						rules={[{ required: true, message: "请选择是否首页显示" }]}
					>
						<Select>
							<Select.Option value={1}>是</Select.Option>
							<Select.Option value={0}>否</Select.Option>
						</Select>
					</Form.Item>

					<Form.Item
						name="status"
						label="状态"
						rules={[{ required: true, message: "请选择状态" }]}
					>
						<Select>
							<Select.Option value={1}>启用</Select.Option>
							<Select.Option value={0}>禁用</Select.Option>
						</Select>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
}
